<?php
/* Please change DB details & check the folder names 
one by one for deletion in the query as well as while deleting below */

$link = mysql_connect('localhost', 'root', 'Enthr@ll99');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('niktemp', $link);
if (!$db_selected) {
    die ('Can\'t use db : ' . mysql_error());
}

$sql = "SELECT meta_value FROM wp_postmeta WHERE meta_key = '_wp_attached_file' AND meta_value LIKE '2011\/07%'";

$result = mysql_query($sql);

if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to send";
    exit;
}

while($row = mysql_fetch_assoc($result)) {
    $preserve[] = str_replace('2011/07/', '', $row['meta_value']);
}

mysql_free_result($result);


$dir = "/var/www/html/buzzr/wp-content/uploads/2011/07/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if(!in_array($file, $preserve) && $file != '.' && $file != '..' ){
              unlink($dir.$file);
              echo "filename: $file : filetype: " . filetype($dir . $file) . " deleted <br />";            }
        }
        closedir($dh);
    }
}
?>
